package com.beauty.dressing.module.market.activity;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.framework.common.utils.ICommonUtil;
import com.framework.common.utils.ILog;
import com.beauty.dressing.R;
import com.beauty.dressing.common.base.BaseActivity;
import com.beauty.dressing.common.bean.BaseBean;
import com.beauty.dressing.common.bean.SalesOrderResp;
import com.beauty.dressing.common.bean.ShopCart;
import com.beauty.dressing.common.interfaces.EventListener;
import com.beauty.dressing.common.interfaces.ShopCarSelectListener;
import com.beauty.dressing.common.utils.Constants;
import com.beauty.dressing.common.utils.ResUtil;
import com.beauty.dressing.common.view.LoadingNodataLayout;
import com.beauty.dressing.library.advrecyclerview.swipeable.RecyclerViewSwipeManager;
import com.beauty.dressing.library.advrecyclerview.touchguard.RecyclerViewTouchActionGuardManager;
import com.beauty.dressing.module.devices.activity.BindDevicesActivity;
import com.beauty.dressing.module.devices.adapter.ConversationAdapter;
import com.beauty.dressing.module.market.adapter.ShopCarAdapter;
import com.beauty.dressing.module.market.presenter.ShopCartPresenter;
import com.beauty.dressing.module.market.presenter.contract.ShopCartContract;
import com.beauty.dressing.rxandroid.rxbus.RxBus;
import com.beauty.dressing.rxandroid.rxbus.RxConstants;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xutingz
 * @E-mail xutz@xianlanba.com
 * @date 2018/5/21
 */

public class ShopCarActivity extends BaseActivity implements ShopCarSelectListener,ShopCartContract.ViewControl{

    private RecyclerView mRecyclerView;
    private RecyclerView.LayoutManager mLayoutManager;
    private ShopCarAdapter mAdapter;
    private RecyclerView.Adapter mWrappedAdapter; //侧滑删除包装类
    private RecyclerViewSwipeManager mRecyclerViewSwipeManager;
    private RecyclerViewTouchActionGuardManager mRecyclerViewTouchActionGuardManager;
    private LoadingNodataLayout mNodtaLayout;
    private TextView mMoneyTxt;
    private ShopCartPresenter mPresenter = new ShopCartPresenter(this);

    private int currentPage = 1;
    public static void startActivity(Context context){
        Intent intent = new Intent(context,ShopCarActivity.class);
        context.startActivity(intent);
    }

    @Override
    public void setContentView() {
        setContentView(R.layout.activity_shop_car);
    }

    @Override
    public void findView() {
        findViewById(R.id.left_img_btn).setOnClickListener(this);
        TextView titleTxt = (TextView) findViewById(R.id.title_txt);
        titleTxt.setText("购物车");
        findViewById(R.id.create_order).setOnClickListener(this);
        mMoneyTxt = findViewById(R.id.money_txt);
        mNodtaLayout = (LoadingNodataLayout) findViewById(R.id.nodata_layout);
        mNodtaLayout.setCenterGravity();
        mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        mLayoutManager = new LinearLayoutManager(context);
        mRecyclerViewTouchActionGuardManager = new RecyclerViewTouchActionGuardManager();
        mRecyclerViewTouchActionGuardManager.setInterceptVerticalScrollingWhileAnimationRunning(true);
        mRecyclerViewTouchActionGuardManager.setEnabled(true);
        mRecyclerViewSwipeManager = new RecyclerViewSwipeManager();
        mRecyclerViewSwipeManager.setOnItemSwipeEventListener(new RecyclerViewSwipeManager.OnItemSwipeEventListener() {
            @Override  //开始滑动时，之前展开的item要关闭回去
            public void onItemSwipeStarted(int position) {
                closeSwipe();
            }

            @Override
            public void onItemSwipeFinished(int position, int result, int afterSwipeReaction) {

            }
        });
        mAdapter = new ShopCarAdapter(context,this);
        mAdapter.setEventListener(new EventListener() {
            @Override
            public void onItemPinned(int position) {
                // item被展开了
            }

            @Override
            public void onItemViewClicked(View v) {
                if (ICommonUtil.isFastDoubleClick()) return;
                boolean hasItemOpen = closeSwipe();
                if (hasItemOpen) {
                    return;
                }
                int position = mRecyclerView.getChildAdapterPosition(v);
                if (position != RecyclerView.NO_POSITION) {
                }
            }

            @Override
            public void onUnderSwipeableViewButtonClicked(View v, View layout) {
                final int position = mRecyclerView.getChildAdapterPosition(layout);
                ILog.w(TAG,"---onUnderSwipeableClicked  position="+position);
                if (position != RecyclerView.NO_POSITION) {
                    final ShopCart item = (ShopCart) mAdapter.getItem(position);
                    switch (v.getId()) {
                        case R.id.delete_txt:
                            //showToast("删除");
                            showProgressDialog();
                            mPresenter.deleteShopcart(item.id);

                            break;
                    }
                }

            }
        });
        mWrappedAdapter = mRecyclerViewSwipeManager.createWrappedAdapter(mAdapter);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setAdapter(mWrappedAdapter);
        mRecyclerViewTouchActionGuardManager.attachRecyclerView(mRecyclerView);
        mRecyclerViewSwipeManager.attachRecyclerView(mRecyclerView);
    }

    @Override
    public void initData() {
        mNodtaLayout.setTitle("暂无购物车信息");
        mNodtaLayout.setIsLoadingUi(true);
        mPresenter.getShopcartList(currentPage);
//        List<ShopCarBean> dbList = controller.getDaoManager().getDaoSession().getShopCarDao().queryAll();
//        if (dbList != null && dbList.size()>0){
//            mAdapter.setList(dbList);
//        } else {
//            mNodtaLayout.setVisibility(View.VISIBLE);
//            mNodtaLayout.setIsLoadingUi(false);
//        }
    }

    /**
     * 关闭滑动块
     */
    private boolean closeSwipe() {
        //关闭其它item
        boolean hasItemOpen = false;
        if (mAdapter != null) {
            int count = mAdapter.getItemCount();
            for (int i = 0; i < count; i++) {
                ShopCart msg = (ShopCart) mAdapter.getItem(i);
                if (msg != null && msg.isPinned()) {
                    msg.setPinned(false);
                    hasItemOpen = true;
                    mAdapter.notifyDataSetChanged();
                    break;
                }
            }
        }
        return hasItemOpen;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.left_img_btn:
                finish();
                break;
            case R.id.create_order:
                showProgressDialog();
                List<ShopCart> list = mAdapter.selectList;
                if (list.isEmpty()){
                    return;
                }
                ShopCart shopCart = list.get(0);
                mPresenter.createOrder(shopCart.id,1);
                break;
        }
    }

    @Override
    public void onShopCarSelect(List<ShopCart> list) {
        if (list == null || list.isEmpty()){
            mMoneyTxt.setText("¥0");
            return;
        } else {
            float money = 0;
            for (ShopCart carBean:list){
                money+= 1;//carBean.price;
            }
            mMoneyTxt.setText("¥"+money);
        }
    }

    @Override
    protected void onDestroy() {
        if (mAdapter != null && mAdapter.getItemCount() >0){
            mAdapter.clearList();
        }
        super.onDestroy();
    }

    @Override
    public void onShopcartList(boolean isSuccess, int code, String message, List<ShopCart> list, int currPage) {
        if (isSuccess){
            currentPage = currPage;
            if (mAdapter.getItemCount() ==0){
                mAdapter.setList(list);
            } else {
                mAdapter.addList(list);
            }
        } else {

        }
        if (mAdapter.getItemCount() ==0){
            mNodtaLayout.setVisibility(View.VISIBLE);
            mNodtaLayout.setIsLoadingUi(false);
        } else {
            mNodtaLayout.setVisibility(View.GONE);
        }

    }

    @Override
    public void onDeleteShopcart(boolean isSuccess, int code, String message, long cartId) {
        dismissProgressDialog();
        if (isSuccess){
            int position = mAdapter.findPositionById(cartId);
            ShopCart item = mAdapter.getItem(position);
            mAdapter.removeShopList(item);
            RecyclerView.ViewHolder holder = mRecyclerView.findViewHolderForAdapterPosition(position);
            if (holder != null){
                mRecyclerViewSwipeManager.removeItemAction(holder,position,0);
            }
            mAdapter.removeItem(position);
            mAdapter.notifyDataSetChanged();
            if (mAdapter.getItemCount() ==0){
                mNodtaLayout.setVisibility(View.VISIBLE);
            }

        } else {
            showToast("删除失败");
        }

    }

    @Override
    public void onCreateOrder(boolean isSuccess, int code, String message, SalesOrderResp data) {
        dismissProgressDialog();
        if (isSuccess && data != null){
            WriteOrderActivity.startActivity(context,data.goods,data.defaAddress != null && !data.defaAddress.isEmpty()?data.defaAddress.get(0):null);
        } else {
            showToast("下单失败");
        }

    }
}
